﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BSCMFF.Core.DataLayer;

namespace BSCMFF.Web.Pages
{
    public partial class UserList1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadGrid1_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            
            int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["User_ID"].ToString());
            BSCEntities context = new BSCEntities();

            User u = (from user in context.Users
                      where user.User_ID == id
                      select user).Single();

            u.Login = (userControl.FindControl("TextBoxLogin") as RadTextBox).Text;
            u.Password = (userControl.FindControl("TextBoxPassword") as RadTextBox).Text;
            u.Role_FK = Convert.ToInt32((userControl.FindControl("ComboBoxRoles") as RadComboBox).SelectedValue);
            context.SaveChanges();
        }

        protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            BSCEntities context = new BSCEntities();

            User u = new User();
            u.Login = (userControl.FindControl("TextBoxLogin") as RadTextBox).Text;
            u.Password = (userControl.FindControl("TextBoxPassword") as RadTextBox).Text;
            u.Role_FK = Convert.ToInt32((userControl.FindControl("ComboBoxRoles") as RadComboBox).SelectedValue);
            u.User_Setting_FK = 1;
            u.Role = new Role();
            context.Users.AddObject(u);

            
                context.SaveChanges();
            
        }

        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);


            int id = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["User_ID"].ToString());
            BSCEntities context = new BSCEntities();

            User u = (from user in context.Users
                      where user.User_ID == id
                      select user).Single();

            context.Users.DeleteObject(u);
            context.SaveChanges();
            RadGrid1.Rebind();
        }

        
    }
}